package handler

import (
	"common/models"
	"net/http"

	"github.com/gin-gonic/gin"
)

type DelAccountBody struct {
	UserName string `json:"user_name" binding:"required"`
}

func AddAccount(c *gin.Context) {
	var addBody models.Account
	if err := c.BindJSON(&addBody); err != nil {
		res := gin.H{
			"msg":    "Invalid params user_name or password",
			"status": -1,
			"result": nil,
		}
		c.JSON(http.StatusBadRequest, res)
		return
	}

	check, err := addBody.AddAccount()
	if err != nil {
		res := gin.H{
			"msg":    err.Error(),
			"status": -1,
			"result": nil,
		}
		c.JSON(http.StatusBadRequest, res)
		return
	}
	if !check {
		res := gin.H{
			"msg":    "账号已存在",
			"status": -1,
			"result": nil,
		}
		c.JSON(http.StatusBadRequest, res)
		return
	}
	res := gin.H{
		"msg":    "succeed",
		"status": 0,
		"result": nil,
	}
	c.JSON(http.StatusOK, res)
}

func LoginAccount(c *gin.Context) {
	var loginBody models.Account
	if err := c.BindJSON(&loginBody); err != nil {
		res := gin.H{
			"msg":    "Invalid params user_name or password",
			"status": -1,
			"result": nil,
		}
		c.JSON(http.StatusBadRequest, res)
		return
	}
	token, msg, err := loginBody.LoginAccount()
	if err != nil {
		res := gin.H{
			"msg":    err.Error(),
			"status": -1,
			"result": nil,
		}
		c.JSON(http.StatusBadRequest, res)
		return
	}
	if token == "" {
		res := gin.H{
			"msg":    msg,
			"status": -1,
			"result": nil,
		}
		c.JSON(http.StatusOK, res)
		return
	}

	res := gin.H{
		"msg":    msg,
		"status": 0,
		"result": map[string]interface{}{
			"token": token,
		},
	}
	c.JSON(http.StatusOK, res)
}

func DelAccount(c *gin.Context) {
	var delBody DelAccountBody
	if err := c.BindJSON(&delBody); err != nil {
		res := gin.H{
			"msg":    "Invalid params user_name",
			"status": -1,
			"result": nil,
		}
		c.JSON(http.StatusBadRequest, res)
		return
	}

	err := models.DelAccount(delBody.UserName)
	if err != nil {
		res := gin.H{
			"msg":    err.Error(),
			"status": -1,
			"result": nil,
		}
		c.JSON(http.StatusBadRequest, res)
		return
	}
	res := gin.H{
		"msg":    "succeed",
		"status": 0,
		"result": nil,
	}
	c.JSON(http.StatusOK, res)
}
